<?php
include_once 'core/Node.php';
include_once 'core/IterativeInterpreter.php';

class ListViewInterpreter extends IterativeInterpreter{
	
	public function interpret(Node $node){
		$childs = $node->getChilds();
		$inset = $node->getAttribute('inset');
		
		$ret = '<ul data-role="listview"';
		if($inset == 'true'){
			$ret .= ' data-inset="true"';
		}		
		$ret .= '>';
		
		foreach ($childs as $child) {
			$name = $child->getAttribute('#');
			if($name == 'item'){
				$ret .= $this->item($child, $node);
			}else{
				$ret .= parent::interpret($child);
			}			
		}
		
		$ret .= '</ul>';
		return $ret;
	}
	
	function item(Node $node, Node $parent){		
		$template = $node->getAttribute('template');
		
		$ret = '';
		if($template != ''){
			$ret .= $this->$template($node, $parent);
		}else{
			$ret .= $this->li($node, $parent);
		}
		return $ret;
	}
	
	function option(Node $node, Node $parent=NULL){
		return $this->external($node, $parent, false);
	}
	
	function external(Node $node, Node $parent=NULL, $ext = true){
		$text = $node->getAttribute('@0');
		$link = $node->getAttribute('@1');
		$icon = $node->getattribute('icon');
						
		$ret = '<li role="option"';
		if($node->hasAttribute('network')){
			$ret .=' network="'.$node->getAttribute('network').'"';
		}
		if($node->hasAttribute('@2')){
			$ret .= ' data-theme="'.$node->getAttribute('@2').'"';
		}
		$ret .= '>';
		
		if($icon != ''){
			$ret .='<img src="'.$icon.'" class="ui-li-icon"/>';
		}
		
		if($link != ''){
			$ret .= '<a href="'.$link.'"';
			if($ext){
				$ret .= ' rel="external"';
			}				
			$ret .= '>';
			$ret .= $text;
			$ret .= '</a>';
		}else{
			$ret .= $text;
		}
		
		$ret .= '</li>';
		return $ret;
	}
	
	function divider(Node $node, Node $parent){
		$text = $node->getAttribute('@0');
		$count = $node->getAttribute('@1');
		
		$ret = '<li data-role="list-divider">';
		if($text != ''){
			$ret .= $text;
		}
		if($count != ''){
			if($count == 'auto'){
				$childs = $parent->getChilds();
				$count = (count($childs)-1);
			}
			$ret.='<span class="ui-li-count">'.$count.'</span>';
		}
		$ret .= '</li>';
		
		return $ret;
	}
	
	function li(Node $node, Node $parent){
		$text = $node->getAttribute('@0');
		$style = $node->getAttribute('style');
		if($text == ''){
			$text = $node->getAttribute('[]');
		}
		
		$ret = '<li data-icon="false"';
		if($style != ''){
			$ret .= ' style="'.$style.'"';
		}
		$ret .= '>';
		
		if($text != ''){
			$ret .= $text;
		}else{
			$ret .=parent::interpret($node);
		}
		$ret .= '</li>';
		return $ret;
	}
}